#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>

const QString& SERVER_IP = "127.0.0.1";
const quint16 SERVER_PORT = 9090;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);

    this->setWindowTitle("客户端");

    connect(socket,&QUdpSocket::readyRead,this,&Widget::processResponse);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    // 1. 获取输入框信息
    QString data = ui->lineEdit->text();
    // 2. 构造数据报
    QNetworkDatagram requestDatagram(data.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);
    // 3. 向服务器发送数据报
    socket->writeDatagram(requestDatagram);
    // 4. 将发送的数据添加在列表框
    ui->listWidget->addItem("客户端说：" + data);
    // 5. 清理输入框信息
    ui->lineEdit->clear();
}

// 处理响应信息
void Widget::processResponse()
{
    // 1. 获取响应信息
    const QNetworkDatagram& text = socket->receiveDatagram();
    QString data = text.data();
    // 2. 将信息输出到列表框
    ui->listWidget->addItem("服务器说：" + data);
}
